/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.ez2find.backing;

import com.ez2find.manager.AreaManagerLocal;
import com.ez2find.manager.PersonalCategorieManagerLocal;
import com.ez2find.manager.PersonalManagerLocal;
import com.ez2find.manager.ImageManagerLocal;
import com.ez2find.manager.LocationManagerLocal;
import com.ez2find.manager.RegisterUserManagerLocal;
import com.ez2find.model.Area;
import com.ez2find.model.Personal;
import com.ez2find.model.PersonalCategorie;
import com.ez2find.model.Image;
import com.ez2find.model.Location;
import com.ez2find.model.RegisterUser;
import com.ez2find.services.EmailLocal;
import com.ez2find.util.RequestContext;
import com.ez2find.util.SessionContext;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.richfaces.model.UploadItem;

/**
 *
 * @author Administrador
 */
public class PersonalBean {

    @EJB
    private PersonalManagerLocal ejbPersonalManager;
    @EJB
    private PersonalCategorieManagerLocal ejbPersonalCategorieManager;
    @EJB
    private RegisterUserManagerLocal ejbUserManager;
    @EJB
    private EmailLocal ejbEmail;
    @EJB
    private AreaManagerLocal ejbAreaManager;
    @EJB
    private LocationManagerLocal ejbLocationManager;
    @EJB
    private ImageManagerLocal ejbImageManager;
    private Personal personal;
    private int back;
    private long personalCategorieId;
    private long areaId;
    private String email1;
    private List<UploadItem> uploadItems;
    private int row;
    private boolean linkRPOk;
    private boolean createOk;
    private int page;
    private String searchValue;
    private String searchMinAge;
    private String searchMaxAge;
    private String searchAm;
    private String searchSeeking;
    private boolean onlySearchTitles;
    private boolean hasImage;

    public Personal getPersonal() {
        if (personal == null) {
            ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
            HttpServletRequest request = (HttpServletRequest) externalContext.getRequest();
            HttpSession session = request.getSession();
            if (session.isNew()) {
                try {
                    String errorPageURL = externalContext.getRequestContextPath() + "/faces/welcome.jsp";
                    externalContext.redirect(errorPageURL);
                    FacesMessage msg = new FacesMessage("The session has bean expired");
                    msg.setSeverity(FacesMessage.SEVERITY_ERROR);
                    FacesContext.getCurrentInstance().addMessage(null, msg);
                    return null;
                } catch (IOException ioe) {
                    ioe.printStackTrace();
                    return null;
                }
            } else {
            SessionBean sessionBean = (SessionBean) SessionContext.getAttribute("sessionBean");
            if (sessionBean.getEjbSession().getPersonal() != null) {
                personal = sessionBean.getEjbSession().getPersonal();
                if(personal.getYourAge()>0)
                    searchMinAge=String.valueOf(personal.getYourAge());
                areaId = 0;
                if (personal.getArea() != null) {
                    areaId = personal.getArea().getId();
                }
                uploadItems = new ArrayList<UploadItem>();
                for (Image img : personal.getImages()) {
                    UploadItem item = new UploadItem("", new File("/home/webadmin/eez2find.com/gfdeploy/site_war/images/" + img.getImage()));
                    uploadItems.add(item);
                }
                personalCategorieId = personal.getPersonalCategorie().getId();
            } else {
                personal = new Personal();
                if (!sessionBean.getAreasCurrentSite().isEmpty()) {
                    if (sessionBean.getEjbSession().getCurrentArea() != null) {
                        areaId = sessionBean.getEjbSession().getCurrentArea().getId();
                    } else {
                        areaId = sessionBean.getEjbSession().getCurrentSite().getAreas().get(1).getId();
                    }
                }
                uploadItems = new ArrayList<UploadItem>();
                try {
                    PostBean postBean = (PostBean) RequestContext.getAttribute("postBean");
                    back = postBean.getBack();
                } catch (Exception ex) {
                }
            }
            }
        }
        return personal;
    }

    public void setPersonal(Personal personal) {
        this.personal = personal;
    }

    public List<Personal> getlistAll() {
        return ejbPersonalManager.listAll();
    }

    public String create() {
        ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
        HttpServletRequest request = (HttpServletRequest) externalContext.getRequest();
        HttpSession session = request.getSession();
        if (session.isNew()) {
          try {
            String errorPageURL = externalContext.getRequestContextPath() + "/faces/personalPosting/create.jsp";
            externalContext.redirect(errorPageURL);
            FacesMessage msg = new FacesMessage("The session has bean expired");
            msg.setSeverity(FacesMessage.SEVERITY_ERROR);
            FacesContext.getCurrentInstance().addMessage(null, msg);
            return null;
          } catch(IOException ioe) {
            ioe.printStackTrace();
            return null;
          }
        } else {
        try {
            SessionBean sessionBean = (SessionBean) SessionContext.getAttribute("sessionBean");
            if (sessionBean.getEjbSession().getOwner() != null) {
                personal.setCode((ejbPersonalManager.lastCode()) + 1);
                personal.setType("personal");
                personal.setUser(sessionBean.getEjbSession().getOwner());
                personal.setEmail(sessionBean.getEjbSession().getOwner().getEmail());
                personal.setTypeReplyTo("masked email");
                ejbEmail.addAnonymousEmail("personal", personal.getCode(), personal.getEmail());
                personal.setPublishDate(new Date(System.currentTimeMillis()));
                personal.setStatus("active");
                personal.setCreateDate(new Date(System.currentTimeMillis()));
                personal.setSite(sessionBean.getEjbSession().getCurrentSite());
                if (searchMinAge != null && !searchMinAge.equals("")) {
                        personal.setYourAge(Integer.parseInt(searchMinAge));
                    } else {
                        personal.setYourAge(0);
                    }
                    if (areaId != 0) {
                    personal.setArea(ejbAreaManager.find(areaId));
                }
                PersonalCategorie personalCategorie = ejbPersonalCategorieManager.find(personalCategorieId);
                personal.setPersonalCategorie(personalCategorie);
                personal.setCategorie(personalCategorie.getCategorie());
                ejbPersonalManager.create(personal);
                if (!uploadItems.isEmpty()) {
                    Personal personalMerge = ejbPersonalManager.merge(personal);
                    long code = ejbImageManager.lastCode() + 1;
                    for (UploadItem item : uploadItems) {
                        BufferedImage personalImage = ImageIO.read(item.getFile());
                        int personalImageWidth;
                        int personalImageHeight;
                        if (personalImage.getWidth() >= personalImage.getHeight()) {
                            personalImageWidth = 300;
                            personalImageHeight = personalImage.getHeight() * 300 / personalImage.getWidth();
                        } else {
                            personalImageHeight = 300;
                            personalImageWidth = personalImage.getWidth() * 300 / personalImage.getHeight();
                        }
                        java.awt.Image image = personalImage.getScaledInstance(personalImageWidth, personalImageHeight, java.awt.Image.SCALE_SMOOTH);
                        BufferedImage scaleImage = new BufferedImage(personalImageWidth, personalImageHeight, BufferedImage.TYPE_INT_RGB);
                        Graphics2D g2d = scaleImage.createGraphics();
                        g2d.drawImage(image, 0, 0, null);
                        g2d.dispose();
                        ImageIO.write(scaleImage, "jpg", new File("/home/webadmin/eez2find.com/gfdeploy/site_war/images/image" + code + ".jpg"));
                        Image i = new Image();
                        i.setCode(code);
                        i.setImage("image" + code + ".jpg");
                        i.setPersonal(personalMerge);
                        ejbImageManager.create(i);
                        personal.getImages().add(i);
                        code++;
                    }
                    personal.setImg(true);
                    ejbPersonalManager.update(personal);
                }
                FacesMessage msg = new FacesMessage("Your post has been successfully registered.");
                FacesContext.getCurrentInstance().addMessage(null, msg);
                FacesMessage msg1 = new FacesMessage("To manage your post,  log into your account.");
                FacesContext.getCurrentInstance().addMessage(null, msg1);
                createOk = true;
                return "success";
            } else {
                if ((personal.getEmail().length() < 4) || !personal.getEmail().contains("@") || !personal.getEmail().contains(".") || (email1.length() < 4) || !email1.contains("@") || !email1.contains(".") || !personal.getEmail().equals(email1)) {
                    FacesMessage msg = new FacesMessage("The emails address don't equals or invalids");
                    msg.setSeverity(FacesMessage.SEVERITY_ERROR);
                    FacesContext.getCurrentInstance().addMessage(null, msg);
                    return null;
                }
                RegisterUser userAccount = ejbUserManager.findUserByEmail(personal.getEmail());
                if (userAccount != null) {
                    if (userAccount.getStatus().equals("active") || userAccount.getStatus().equals("reactive")) {
                        personal.setUser(userAccount);
                        personal.setCode((ejbPersonalManager.lastCode()) + 1);
                        personal.setType("personal");
                        personal.setTypeReplyTo("masked email");
                        personal.setStatus("pending");
                        personal.setCreateDate(new Date(System.currentTimeMillis()));
                        personal.setSite(sessionBean.getEjbSession().getCurrentSite());
                        if (searchMinAge != null && !searchMinAge.equals("")) {
                        personal.setYourAge(Integer.parseInt(searchMinAge));
                    } else {
                        personal.setYourAge(0);
                    }
                    if (areaId != 0) {
                            personal.setArea(ejbAreaManager.find(areaId));
                        }
                        PersonalCategorie personalCategorie = ejbPersonalCategorieManager.find(personalCategorieId);
                        personal.setPersonalCategorie(personalCategorie);
                        personal.setCategorie(personalCategorie.getCategorie());
                        ejbPersonalManager.create(personal);
                        if (!uploadItems.isEmpty()) {
                            Personal personalMerge = ejbPersonalManager.merge(personal);
                            long code = ejbImageManager.lastCode() + 1;
                            for (UploadItem item : uploadItems) {
                                BufferedImage personalImage = ImageIO.read(item.getFile());
                                int personalImageWidth;
                                int personalImageHeight;
                                if (personalImage.getWidth() >= personalImage.getHeight()) {
                                    personalImageWidth = 300;
                                    personalImageHeight = personalImage.getHeight() * 300 / personalImage.getWidth();
                                } else {
                                    personalImageHeight = 300;
                                    personalImageWidth = personalImage.getWidth() * 300 / personalImage.getHeight();
                                }
                                java.awt.Image image = personalImage.getScaledInstance(personalImageWidth, personalImageHeight, java.awt.Image.SCALE_SMOOTH);
                                BufferedImage scaleImage = new BufferedImage(personalImageWidth, personalImageHeight, BufferedImage.TYPE_INT_RGB);
                                Graphics2D g2d = scaleImage.createGraphics();
                                g2d.drawImage(image, 0, 0, null);
                                g2d.dispose();
                                ImageIO.write(scaleImage, "jpg", new File("/home/webadmin/eez2find.com/gfdeploy/site_war/images/image" + code + ".jpg"));
                                Image i = new Image();
                                i.setCode(code);
                                i.setImage("image" + code + ".jpg");
                                i.setPersonal(personalMerge);
                                ejbImageManager.create(i);
                                personal.getImages().add(i);
                                code++;
                            }
                            personal.setImg(true);
                            ejbPersonalManager.update(personal);
                        }
                        FacesMessage msg = new FacesMessage("Your post has been successfully registered.");
                        FacesContext.getCurrentInstance().addMessage(null, msg);
                        FacesMessage msg1 = new FacesMessage("The User Account from this email " + userAccount.getEmail() + " exist.");
                        FacesContext.getCurrentInstance().addMessage(null, msg1);
                        FacesMessage msg2 = new FacesMessage("If you forgot your password or need to reactive your account clik in the link to recovery password.");
                        FacesContext.getCurrentInstance().addMessage(null, msg2);
                        FacesMessage msg3 = new FacesMessage("Please enter in your account and published your posting.");
                        FacesContext.getCurrentInstance().addMessage(null, msg3);
                        linkRPOk = true;
                        createOk = true;
                        return "success";
                    }
                    //userAccount.setDefaultSite(sessionBean.getEjbSession().getCurrentSite());
                    userAccount.setRegisterDate(new Date(System.currentTimeMillis()));
                    Random r = new Random();
                    String token = Long.toString(Math.abs(r.nextLong()), 36);
                    userAccount.setConfirmationCode(token);
                    ejbUserManager.update(userAccount, false);
                    ejbEmail.sendAccountConfirmation(userAccount);
                    personal.setUser(userAccount);
                } else {
                    RegisterUser registerUser = new RegisterUser();
                    registerUser.setEmail(personal.getEmail());
                    //registerUser.setDefaultSite(sessionBean.getEjbSession().getCurrentSite());
                    registerUser.setNumberOfPostings(50);
                    registerUser.setRegisterDate(new Date(System.currentTimeMillis()));
                    registerUser.setStatus("pending");
                    Random r = new Random();
                    String token = Long.toString(Math.abs(r.nextLong()), 36);
                    registerUser.setConfirmationCode(token);
                    ejbUserManager.create(registerUser);
                    RegisterUser newRegisterUser = ejbUserManager.merge(registerUser);
                    ejbEmail.sendAccountConfirmation(newRegisterUser);
                    personal.setUser(newRegisterUser);
                }
                personal.setCode((ejbPersonalManager.lastCode()) + 1);
                personal.setType("personal");
                personal.setTypeReplyTo("masked email");
                personal.setStatus("pending");
                personal.setCreateDate(new Date(System.currentTimeMillis()));
                personal.setSite(sessionBean.getEjbSession().getCurrentSite());
                if (searchMinAge != null && !searchMinAge.equals("")) {
                        personal.setYourAge(Integer.parseInt(searchMinAge));
                    } else {
                        personal.setYourAge(0);
                    }
                    if (areaId != 0) {
                    personal.setArea(ejbAreaManager.find(areaId));
                }
                PersonalCategorie personalCategorie = ejbPersonalCategorieManager.find(personalCategorieId);
                personal.setPersonalCategorie(personalCategorie);
                personal.setCategorie(personalCategorie.getCategorie());
                ejbPersonalManager.create(personal);
                if (!uploadItems.isEmpty()) {
                    Personal personalMerge = ejbPersonalManager.merge(personal);
                    long code = ejbImageManager.lastCode() + 1;
                    for (UploadItem item : uploadItems) {
                        BufferedImage personalImage = ImageIO.read(item.getFile());
                        int personalImageWidth;
                        int personalImageHeight;
                        if (personalImage.getWidth() >= personalImage.getHeight()) {
                            personalImageWidth = 300;
                            personalImageHeight = personalImage.getHeight() * 300 / personalImage.getWidth();
                        } else {
                            personalImageHeight = 300;
                            personalImageWidth = personalImage.getWidth() * 300 / personalImage.getHeight();
                        }
                        java.awt.Image image = personalImage.getScaledInstance(personalImageWidth, personalImageHeight, java.awt.Image.SCALE_SMOOTH);
                        BufferedImage scaleImage = new BufferedImage(personalImageWidth, personalImageHeight, BufferedImage.TYPE_INT_RGB);
                        Graphics2D g2d = scaleImage.createGraphics();
                        g2d.drawImage(image, 0, 0, null);
                        g2d.dispose();
                        ImageIO.write(scaleImage, "jpg", new File("/home/webadmin/eez2find.com/gfdeploy/site_war/images/image" + code + ".jpg"));
                        Image i = new Image();
                        i.setCode(code);
                        i.setImage("image" + code + ".jpg");
                        i.setPersonal(personalMerge);
                        ejbImageManager.create(i);
                        personal.getImages().add(i);
                        code++;
                    }
                    personal.setImg(true);
                    ejbPersonalManager.update(personal);
                }
                FacesMessage msg = new FacesMessage("Your post has been successfully registered.");
                FacesContext.getCurrentInstance().addMessage(null, msg);
                FacesMessage msg1 = new FacesMessage("For Administrate your Post eez2find creates an Account for you using the email address " + personal.getEmail() + " to reply this post.");
                FacesContext.getCurrentInstance().addMessage(null, msg1);
                FacesMessage msg2 = new FacesMessage("Please active your account from email received and published your posting.");
                FacesContext.getCurrentInstance().addMessage(null, msg2);
                createOk = true;
                return "success";
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            FacesMessage msg = new FacesMessage("Error your Post can't register, maybe the email could not be sent or it doesn't exist");
            msg.setSeverity(FacesMessage.SEVERITY_ERROR);
            FacesContext.getCurrentInstance().addMessage(null, msg);
            return null;
        }
        }
    }

    public String previewCreate() {
        ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
        HttpServletRequest request = (HttpServletRequest) externalContext.getRequest();
        HttpSession session = request.getSession();
        if (session.isNew()) {
          try {
            String errorPageURL = externalContext.getRequestContextPath() + "/faces/personalPosting/create.jsp";
            externalContext.redirect(errorPageURL);
            FacesMessage msg = new FacesMessage("The session has bean expired");
            msg.setSeverity(FacesMessage.SEVERITY_ERROR);
            FacesContext.getCurrentInstance().addMessage(null, msg);
            return null;
          } catch(IOException ioe) {
            ioe.printStackTrace();
            return null;
          }
        } else {
        SessionBean sessionBean = (SessionBean) SessionContext.getAttribute("sessionBean");
        if (sessionBean.getEjbSession().getOwner() != null) {
            personal.setEmail(sessionBean.getEjbSession().getOwner().getEmail());
            if (searchMinAge != null && !searchMinAge.equals("")) {
                        personal.setYourAge(Integer.parseInt(searchMinAge));
                    } else {
                        personal.setYourAge(0);
                    }
                    return "success";
        } else {
            if ((personal.getEmail().length() < 4) || !personal.getEmail().contains("@") || !personal.getEmail().contains(".") || (email1.length() < 4) || !email1.contains("@") || !email1.contains(".") || !personal.getEmail().equals(email1)) {
                FacesMessage msg = new FacesMessage("The emails address don't equals or invalids");
                msg.setSeverity(FacesMessage.SEVERITY_ERROR);
                FacesContext.getCurrentInstance().addMessage(null, msg);
                return null;
            }
            if (searchMinAge != null && !searchMinAge.equals("")) {
                        personal.setYourAge(Integer.parseInt(searchMinAge));
                    } else {
                        personal.setYourAge(0);
                    }
                    return "success";
        }
        }
    }

    public String update() {
        ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
        HttpServletRequest request = (HttpServletRequest) externalContext.getRequest();
        HttpSession session = request.getSession();
        if (session.isNew()) {
          try {
            String errorPageURL = externalContext.getRequestContextPath() + "/faces/welcome.jsp";
            externalContext.redirect(errorPageURL);
            FacesMessage msg = new FacesMessage("The session has bean expired");
            msg.setSeverity(FacesMessage.SEVERITY_ERROR);
            FacesContext.getCurrentInstance().addMessage(null, msg);
            return null;
          } catch(IOException ioe) {
            ioe.printStackTrace();
            return null;
          }
        } else {
        try {
            SessionBean sessionBean = (SessionBean) SessionContext.getAttribute("sessionBean");
            if (searchMinAge != null && !searchMinAge.equals("")) {
                        personal.setYourAge(Integer.parseInt(searchMinAge));
                    } else {
                        personal.setYourAge(0);
                    }
                    if (areaId != 0) {
                personal.setArea(ejbAreaManager.find(areaId));
            } else {
                personal.setArea(null);
            }
            PersonalCategorie personalCategorie = ejbPersonalCategorieManager.find(personalCategorieId);
            personal.setPersonalCategorie(personalCategorie);
            personal.setCategorie(personalCategorie.getCategorie());
            if (personal.getImages().isEmpty()) {
                if (!uploadItems.isEmpty()) {
                    long code = ejbImageManager.lastCode() + 1;
                    for (UploadItem item : uploadItems) {
                        BufferedImage personalImage = ImageIO.read(item.getFile());
                        int personalImageWidth;
                        int personalImageHeight;
                        if (personalImage.getWidth() >= personalImage.getHeight()) {
                            personalImageWidth = 300;
                            personalImageHeight = personalImage.getHeight() * 300 / personalImage.getWidth();
                        } else {
                            personalImageHeight = 300;
                            personalImageWidth = personalImage.getWidth() * 300 / personalImage.getHeight();
                        }
                        java.awt.Image image = personalImage.getScaledInstance(personalImageWidth, personalImageHeight, java.awt.Image.SCALE_SMOOTH);
                        BufferedImage scaleImage = new BufferedImage(personalImageWidth, personalImageHeight, BufferedImage.TYPE_INT_RGB);
                        Graphics2D g2d = scaleImage.createGraphics();
                        g2d.drawImage(image, 0, 0, null);
                        g2d.dispose();
                        ImageIO.write(scaleImage, "jpg", new File("/home/webadmin/eez2find.com/gfdeploy/site_war/images/image" + code + ".jpg"));
                        Image i = new Image();
                        i.setCode(code);
                        i.setImage("image" + code + ".jpg");
                        i.setPersonal(personal);
                        ejbImageManager.create(i);
                        personal.getImages().add(i);
                        code++;
                    }
                    personal.setImg(true);
                }
            } else {
                if (!uploadItems.isEmpty()) {
                    long code = ejbImageManager.lastCode() + 1;
                    int index = 0;
                    for (UploadItem item : uploadItems) {
                        if (!item.getFileName().equals("")) {
                            BufferedImage personalImage = ImageIO.read(item.getFile());
                            int personalImageWidth;
                            int personalImageHeight;
                            if (personalImage.getWidth() >= personalImage.getHeight()) {
                                personalImageWidth = 300;
                                personalImageHeight = personalImage.getHeight() * 300 / personalImage.getWidth();
                            } else {
                                personalImageHeight = 300;
                                personalImageWidth = personalImage.getWidth() * 300 / personalImage.getHeight();
                            }
                            java.awt.Image image = personalImage.getScaledInstance(personalImageWidth, personalImageHeight, java.awt.Image.SCALE_SMOOTH);
                            BufferedImage scaleImage = new BufferedImage(personalImageWidth, personalImageHeight, BufferedImage.TYPE_INT_RGB);
                            Graphics2D g2d = scaleImage.createGraphics();
                            g2d.drawImage(image, 0, 0, null);
                            g2d.dispose();
                            if (index < personal.getImages().size()) {
                                ImageIO.write(scaleImage, "jpg", new File("/home/webadmin/eez2find.com/gfdeploy/site_war/images/image" + personal.getImages().get(index).getCode() + ".jpg"));
                            } else {
                                ImageIO.write(scaleImage, "jpg", new File("/home/webadmin/eez2find.com/gfdeploy/site_war/images/image" + code + ".jpg"));
                                Image i = new Image();
                                i.setCode(code);
                                i.setImage("image" + code + ".jpg");
                                i.setPersonal(personal);
                                ejbImageManager.create(i);
                                personal.getImages().add(i);
                                code++;
                            }
                        }
                        index++;
                    }
                    for (int i = index; i < personal.getImages().size(); i++) {
                        File f = new File("/home/webadmin/eez2find.com/gfdeploy/site_war/images/" + personal.getImages().get(i).getImage());
                        f.delete();
                        ejbImageManager.delete(personal.getImages().get(i));
                        personal.getImages().remove(i);
                    }
                } else {
                    for (Image img : personal.getImages()) {
                        File f = new File("/home/webadmin/eez2find.com/gfdeploy/site_war/images/" + img.getImage());
                        f.delete();
                        ejbImageManager.delete(img);
                    }
                    personal.getImages().clear();
                    personal.setImg(false);
                }
            }
            ejbPersonalManager.update(personal);
            FacesMessage msg = new FacesMessage("Successful edit your Post");
            FacesContext.getCurrentInstance().addMessage(null, msg);
            sessionBean.getEjbSession().setPersonal(null);
            SessionContext.removeAttribute("personalBean");
            return "success";
        } catch (Exception ex) {
            ex.printStackTrace();
            FacesMessage msg = new FacesMessage("Error your Post can't edit");
            msg.setSeverity(FacesMessage.SEVERITY_ERROR);
            FacesContext.getCurrentInstance().addMessage(null, msg);
            return null;
        }
        }
    }

    public String previewUpdate() {
        if (searchMinAge != null && !searchMinAge.equals("")) {
                        personal.setYourAge(Integer.parseInt(searchMinAge));
                    } else {
                        personal.setYourAge(0);
                    }
                    return "previewUpdate";
    }
    
    public long getAreaId() {
        return areaId;
    }

    public void setAreaId(long areaId) {
        this.areaId = areaId;
    }

    public Area getArea() {
        return ejbAreaManager.find(areaId);
    }

    public List<Location> getLocationsPersonalArea() {
        try {
            return ejbLocationManager.locationsArea(ejbAreaManager.find(areaId));
        } catch (Exception ex) {
            return new ArrayList<Location>();
        }
    }

    public boolean isCreateOk() {
        return createOk;
    }

    public void setCreateOk(boolean createOk) {
        this.createOk = createOk;
    }

    public boolean isLinkRPOk() {
        return linkRPOk;
    }

    public void setLinkRPOk(boolean linkRPOk) {
        this.linkRPOk = linkRPOk;
    }

    public String homeUser() {
        SessionContext.removeAttribute("personalBean");
        return "homeUser";
    }

    public int getBack() {
        return back;
    }

    public void setBack(int back) {
        this.back = back;
    }

    public long getPersonalCategorieId() {
        if (personalCategorieId == 0) {
            try {
                PostBean postBean = (PostBean) RequestContext.getAttribute("postBean");
                personalCategorieId = postBean.getCategorieId();
            } catch (Exception ex) {
            }
        }
        return personalCategorieId;
    }

    public void setPersonalCategorieId(long personalCategorieId) {
        this.personalCategorieId = personalCategorieId;
    }

    public List<Personal> getListPersonals() {
        ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
        HttpServletRequest request = (HttpServletRequest) externalContext.getRequest();
        HttpSession session = request.getSession();
        if (session.isNew()) {
          try {
            String errorPageURL = externalContext.getRequestContextPath() + "/faces/personalPosting/list.jsp";
            externalContext.redirect(errorPageURL);
            FacesMessage msg = new FacesMessage("The session has bean expired");
            msg.setSeverity(FacesMessage.SEVERITY_ERROR);
            FacesContext.getCurrentInstance().addMessage(null, msg);
            return null;
          } catch(IOException ioe) {
            ioe.printStackTrace();
            return null;
          }
        } else {
        String consult = "";
        boolean personalC = false;
        if (personalCategorieId > 0) {
            consult = consult + " AND p.personalCategorie=:personalCategorie";
            personalC = true;
        }
        if (searchAm != null && !searchAm.equals("")){
            consult = consult + " AND p.am='"+searchAm+"'";
        }
        if (searchSeeking != null && !searchSeeking.equals("")) {
             consult = consult + " AND p.seeking='"+searchSeeking+"'";
         }
        if (searchMinAge != null && !searchMinAge.equals("") && searchMaxAge != null && !searchMaxAge.equals("") && Double.parseDouble(searchMinAge) > Double.parseDouble(searchMaxAge)) {
            FacesMessage msg = new FacesMessage("The min age should be smaller than max age");
            msg.setSeverity(FacesMessage.SEVERITY_ERROR);
            FacesContext.getCurrentInstance().addMessage(null, msg);
        } else if ((searchMinAge != null && !searchMinAge.equals("")) || (searchMaxAge != null && !searchMaxAge.equals(""))) {
            if (searchMinAge != null && !searchMinAge.equals("")) {
                consult = consult + " AND p.price>=" + searchMinAge;
            } else {
                consult = consult + " AND p.price>0";
            }
            if (searchMaxAge != null && !searchMaxAge.equals("")) {
                consult = consult + " AND p.price<=" + searchMaxAge;
            }
        }
        if (hasImage) {
            consult = consult + " AND (p.description like '%<img src=%' OR p.img=1)";
        }
        if (searchValue != null && !searchValue.equals("")) {
            if (onlySearchTitles) {
                consult = consult + " AND p.title like '%" + searchValue + "%'";
            } else {
                consult = consult + " AND (p.title like '%" + searchValue + "%' OR p.description like '%" + searchValue + "%')";
            }
        }
        SessionBean sessionBean = (SessionBean) SessionContext.getAttribute("sessionBean");
        if (sessionBean.getEjbSession().getCurrentArea() == null) {
            return ejbPersonalManager.listPersonalsSite(sessionBean.getEjbSession().getCurrentSite(), personalC, ejbPersonalCategorieManager.find(personalCategorieId), consult);
        } else {
            return ejbPersonalManager.listPersonalsArea(sessionBean.getEjbSession().getCurrentArea(), personalC, ejbPersonalCategorieManager.find(personalCategorieId), consult);
        }
        }
    }

    public String backView() {
        personal = null;
        return "backPersonal" + back;
    }

    public String backCreate() {
        SessionContext.removeAttribute("personalBean");
        return "back" + back;
    }

    public String backEdit() {
        SessionContext.removeAttribute("personalBean");
        return "back";
    }

    public String getEmail1() {
        return email1;
    }

    public void setEmail1(String email1) {
        this.email1 = email1;
    }

    public Date getToDay() {
        return new Date(System.currentTimeMillis());
    }

    public String getDescription() {
        try {
            if (personal.getDescription().contains("\n")) {
                return personal.getDescription().replaceAll("\n", "<br/>");
            } else {
                return personal.getDescription().replaceAll("\r", "<br/>");
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            return "Do not Message";
        }
    }

    public String getSearchValue() {
        if(searchValue==null){
            try {
                PostBean postBean = (PostBean) RequestContext.getAttribute("postBean");
                searchValue = postBean.getSearchValue();
            } catch (Exception ex) {
            }
        }
        return searchValue;
    }

    public void setSearchValue(String searchValue) {
        this.searchValue = searchValue;
    }

    public boolean isOnlySearchTitles() {
        return onlySearchTitles;
    }

    public void setOnlySearchTitles(boolean onlySearchTitles) {
        this.onlySearchTitles = onlySearchTitles;
    }

    public boolean isHasImage() {
        return hasImage;
    }

    public void setHasImage(boolean hasImage) {
        this.hasImage = hasImage;
    }

    public void paint(OutputStream out, Object data) throws IOException {
        UploadItem item = uploadItems.get((Integer) data);
        BufferedImage img = ImageIO.read(item.getFile());
        int imgWidth;
        int imgHeight;
        if (img.getWidth() >= img.getHeight()) {
            imgWidth = 100;
            imgHeight = img.getHeight() * 100 / img.getWidth();
        } else {
            imgHeight = 100;
            imgWidth = img.getWidth() * 100 / img.getHeight();
        }
        java.awt.Image image = img.getScaledInstance(imgWidth, imgHeight, java.awt.Image.SCALE_SMOOTH);
        BufferedImage scaleImg = new BufferedImage(imgWidth, imgHeight, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2d = scaleImg.createGraphics();
        g2d.drawImage(image, 0, 0, null);
        g2d.dispose();

        ImageIO.write(scaleImg, "jpg", out);
    }

    public void paintPreview(OutputStream out, Object data) throws IOException {
        UploadItem item = uploadItems.get((Integer) data);
        BufferedImage img = ImageIO.read(item.getFile());
        int imgWidth;
        int imgHeight;
        if (img.getWidth() >= img.getHeight()) {
            imgWidth = 300;
            imgHeight = img.getHeight() * 300 / img.getWidth();
        } else {
            imgHeight = 300;
            imgWidth = img.getWidth() * 300 / img.getHeight();
        }
        java.awt.Image image = img.getScaledInstance(imgWidth, imgHeight, java.awt.Image.SCALE_SMOOTH);
        BufferedImage scaleImg = new BufferedImage(imgWidth, imgHeight, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2d = scaleImg.createGraphics();
        g2d.drawImage(image, 0, 0, null);
        g2d.dispose();

        ImageIO.write(scaleImg, "jpg", out);
    }
    
    public void deleteItem() {
        uploadItems.remove(row);
    }

    public void deleteItems() {
        uploadItems.clear();
    }

    public int getItemsSize() {
        return uploadItems.size();
    }

    public List<UploadItem> getUploadItems() {
        return uploadItems;
    }

    public void setUploadItems(List<UploadItem> uploadItems) {
        this.uploadItems = uploadItems;
    }

    public int getRow() {
        return row;
    }

    public void setRow(int row) {
        this.row = row;
    }

    public int getPage() {
        if(page==0)
            page=1;
        return page;
    }

    public void setPage(int page) {
        this.page = page;
    }

    public String getSearchMinAge() {
        return searchMinAge;
    }

    public void setSearchMinAge(String searchMinAge) {
        this.searchMinAge = searchMinAge;
    }

    public String getSearchMaxAge() {
        return searchMaxAge;
    }

    public void setSearchMaxAge(String searchMaxAge) {
        this.searchMaxAge = searchMaxAge;
    }

    public String getSearchSeeking() {
        return searchSeeking;
    }

    public void setSearchSeeking(String searchSeeking) {
        this.searchSeeking = searchSeeking;
    }

    public String getSearchAm() {
        return searchAm;
    }

    public void setSearchAm(String searchAm) {
        this.searchAm = searchAm;
    }
    
    public int getContador(){
        try{
            return 20000-personal.getDescription().length();
        }catch(Exception ex){
            return 20000;
        }
    }
    
    public void setContador(int contador){}
    

    public void flaggingMiscategorized(){
        try {
            personal.setMiscategorized(ejbPersonalManager.merge(personal).getMiscategorized()+1);
            ejbPersonalManager.update(personal);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    
    public void flaggingProhibited(){
        try {
            personal.setProhibited(ejbPersonalManager.merge(personal).getProhibited()+1);
            ejbPersonalManager.update(personal);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    
    public void flaggingSpam(){
        try {
            personal.setSpam(ejbPersonalManager.merge(personal).getSpam()+1);
            ejbPersonalManager.update(personal);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    
    public void flaggingBest(){
        try {
            personal.setBest(ejbPersonalManager.merge(personal).getBest()+1);
            ejbPersonalManager.update(personal);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}
